<template>
    <!-- 弹出层容器 -->
    <div class="social-login-modal" @click.self="handleClose">
        <!-- 关闭按钮 -->
        <button @click="handleClose" class="close-btn">
            <i class="fa fa-times"></i>
        </button>

        <div class="social-login-container">
            <!-- 登录标题 -->
            <div class="login-header">
                <i class="fa fa-weixin text-4xl text-green-500 mb-4"></i>
                <h2 class="text-xl font-bold text-gray-800 mb-2">微信登录</h2>
                <p class="text-gray-600">{{ isWechatBrowser ? '请授权获取您的微信信息' : '请使用微信扫描二维码登录' }}</p>
            </div>

            <!-- PC端扫码登录 -->
            <div v-if="!isWechatBrowser" class="pc-login">
                <div class="qrcode-section">
                    <div class="qrcode-wrapper">
                        <div v-if="qrCodeUrl" class="qrcode-container">
                            <img :src="qrCodeUrl" alt="微信登录二维码" class="qrcode-image" />
                            <div v-if="qrExpired" class="qrcode-overlay">
                                <p class="text-sm text-gray-600 mb-2">二维码已过期</p>
                                <button @click="refreshQrCode" class="refresh-btn">
                                    <i class="fa fa-refresh mr-1"></i>
                                    刷新二维码
                                </button>
                            </div>
                        </div>
                        <div v-else class="qrcode-loading">
                            <i class="fa fa-spinner fa-spin text-3xl text-gray-400"></i>
                            <p class="text-sm text-gray-600 mt-2">正在生成二维码...</p>
                        </div>
                    </div>

                    <div class="qrcode-tips">
                        <div class="tip-item">
                            <i class="fa fa-mobile-alt text-green-500"></i>
                            <span>打开微信</span>
                        </div>
                        <div class="tip-item">
                            <i class="fa fa-qrcode text-blue-500"></i>
                            <span>扫描二维码</span>
                        </div>
                        <div class="tip-item">
                            <i class="fa fa-check-circle text-purple-500"></i>
                            <span>确认登录</span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 微信端直接授权 -->
            <div v-else class="wechat-auth">
                <div class="auth-info">
                    <div class="info-item">
                        <i class="fa fa-user text-blue-500"></i>
                        <span>获取您的微信信息进行登录</span>
                    </div>
                    <div class="info-item">
                        <i class="fa fa-shield text-green-500"></i>
                        <span>安全登录，保护您的隐私</span>
                    </div>
                </div>

                <div class="auth-actions">
                    <button @click="handleWechatAuth" class="auth-btn">
                        <i class="fa fa-weixin mr-2"></i>
                        微信授权登录
                    </button>
                </div>
            </div>

            <!-- 登录状态提示 -->
            <div v-if="showResult" class="login-result">
                <div class="result-content">
                    <i :class="resultIcon" class="result-icon"></i>
                    <h3 class="result-title">{{ resultTitle }}</h3>
                    <p class="result-message">{{ resultMessage }}</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserInfo } from '/@/stores/userInfo'
import { ElMessage } from 'element-plus'
import { getWechatQrCode, checkWechatQrLogin, getWechatAuthUrl, loginByTempToken } from '/@/api/frontend/enneagram/wechat'

// 定义 emits
const emit = defineEmits(['success', 'error', 'close'])

// 响应式数据
const router = useRouter()
const userInfo = useUserInfo()

// 微信相关状态
const isWechatBrowser = ref(false)
const qrCodeUrl = ref('')
const qrExpired = ref(false)
const qrScene = ref('')
const checkTimer = ref<number | null>(null)

// 登录状态
const showResult = ref(false)
const resultTitle = ref('')
const resultMessage = ref('')
const resultIcon = ref('')

// 检测是否为微信浏览器
const detectWechatBrowser = () => {
    const ua = navigator.userAgent.toLowerCase()
    isWechatBrowser.value = ua.includes('micromessenger')
}

// 生成场景值
const generateScene = () => {
    return 'wechat_login_' + Date.now() + '_' + Math.random().toString(36).slice(2, 11)
}

// 生成微信二维码
const generateQrCode = async () => {
    try {
        qrExpired.value = false
        qrScene.value = generateScene()

        const result = await getWechatQrCode({
            scene: qrScene.value,
            expire_seconds: 600,
        })

        if (result.code === 1) {
            qrCodeUrl.value = result.data.qr_url
            startQrCheck()
        } else {
            ElMessage.error(result.msg || '生成微信二维码失败')
        }
    } catch (error) {
        ElMessage.error('生成微信二维码失败')
        console.error('生成微信二维码失败:', error)
    }
}

// 开始检查二维码登录状态
const startQrCheck = () => {
    if (checkTimer.value) {
        clearInterval(checkTimer.value)
    }

    checkTimer.value = window.setInterval(async () => {
        try {
            const result = await checkWechatQrLogin({
                scene: qrScene.value,
            })

            if (result.code === 1 && result.data) {
                clearInterval(checkTimer.value!)
                handleLoginResult(result.data)
            }
        } catch (error) {
            console.error('检查微信登录状态失败:', error)
        }
    }, 2000)

    // 10分钟后停止检查并标记过期
    setTimeout(() => {
        if (checkTimer.value) {
            clearInterval(checkTimer.value)
            qrExpired.value = true
        }
    }, 600000)
}

// 刷新二维码
const refreshQrCode = () => {
    generateQrCode()
}

// 微信端直接授权登录
const handleWechatAuth = async () => {
    try {
        const result = await getWechatAuthUrl()

        if (result.code === 1) {
            window.location.href = result.data.auth_url
        } else {
            ElMessage.error('获取微信授权URL失败')
        }
    } catch (error) {
        ElMessage.error('微信授权失败')
        console.error('微信授权失败:', error)
    }
}

// 处理登录结果
const handleLoginResult = (result: any) => {
    if (result.success) {
        showLoginResult('success', '登录成功', '欢迎回来！')

        // 使用系统原有的登录成功逻辑
        if (result.token) {
            // 触发系统的登录成功处理
            emit('success', result)

            setTimeout(() => {
                router.push('/index')
                handleClose()
            }, 1500)
        }
    } else {
        showLoginResult('error', '登录失败', result.message || '登录失败，请重试')
    }
}

// 检测URL中的微信授权回调参数
const checkWechatCallback = async () => {
    const urlParams = new URLSearchParams(window.location.search)
    const wechatLoginToken = urlParams.get('wechat_login_token')
    const error = urlParams.get('error')

    if (wechatLoginToken) {
        try {
            showLoginResult('loading', '正在登录...', '正在验证微信授权信息')

            const result = await loginByTempToken({
                temp_token: wechatLoginToken,
            })

            if (result.code === 1) {
                showLoginResult('success', '微信登录成功', '欢迎回来！')

                // 清理URL参数
                cleanUrlParams(['wechat_login_token'])

                // 使用系统原有的登录成功逻辑
                emit('success', result.data)
            } else {
                showLoginResult('error', '登录失败', result.msg || '微信登录验证失败')
                cleanUrlParams(['wechat_login_token'])
            }
        } catch (error) {
            showLoginResult('error', '登录失败', '网络错误，请重试')
            cleanUrlParams(['wechat_login_token'])
            console.error('临时凭证登录失败:', error)
        }
    } else if (error) {
        showLoginResult('error', '授权失败', decodeURIComponent(error))
        cleanUrlParams(['error'])
    }
}

// 显示登录结果
const showLoginResult = (type: 'success' | 'error' | 'loading', title: string, message: string) => {
    resultTitle.value = title
    resultMessage.value = message

    switch (type) {
        case 'success':
            resultIcon.value = 'fa fa-check-circle text-green-500'
            break
        case 'error':
            resultIcon.value = 'fa fa-times-circle text-red-500'
            break
        case 'loading':
            resultIcon.value = 'fa fa-spinner fa-spin text-blue-500'
            break
    }

    showResult.value = true
}

// 清理URL参数
const cleanUrlParams = (params: string[]) => {
    const url = new URL(window.location.href)
    params.forEach((param) => {
        url.searchParams.delete(param)
    })
    window.history.replaceState({}, document.title, url.toString())
}

// 关闭弹窗
const handleClose = () => {
    emit('close')
}

// 清理定时器
const clearTimer = () => {
    if (checkTimer.value) {
        clearInterval(checkTimer.value)
        checkTimer.value = null
    }
}

// 生命周期
onMounted(() => {
    detectWechatBrowser()
    checkWechatCallback()

    // 如果是PC端，生成二维码
    if (!isWechatBrowser.value) {
        generateQrCode()
    }
})

onUnmounted(() => {
    clearTimer()
})
</script>

<style scoped>
.social-login-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.6);
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 1rem;
    z-index: 1000;
    backdrop-filter: blur(4px);
}

.close-btn {
    position: absolute;
    top: 20px;
    right: 20px;
    width: 40px;
    height: 40px;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 20px;
    cursor: pointer;
    border: none;
    z-index: 1001;
    transition: all 0.3s ease;
}

.close-btn:hover {
    background-color: rgba(255, 255, 255, 0.3);
    transform: scale(1.1);
}

.social-login-container {
    background: white;
    border-radius: 16px;
    box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    overflow: hidden;
    max-width: 480px;
    width: 100%;
    max-height: 90vh;
    overflow-y: auto;
    position: relative;
}

/* 登录标题样式 */
.login-header {
    text-align: center;
    padding: 2rem 2rem 1rem;
    background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
}

.login-header i {
    display: block;
    margin: 0 auto 1rem;
}

/* PC端登录样式 */
.pc-login {
    padding: 1rem 2rem 2rem;
}

.qrcode-section {
    text-align: center;
}

.qrcode-wrapper {
    margin-bottom: 1.5rem;
}

.qrcode-container {
    position: relative;
    display: inline-block;
    padding: 1rem;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    background: white;
}

.qrcode-image {
    width: 200px;
    height: 200px;
    display: block;
}

.qrcode-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.95);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    border-radius: 10px;
}

.refresh-btn {
    background: #3b82f6;
    color: white;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    cursor: pointer;
    font-size: 0.875rem;
    transition: background-color 0.2s;
}

.refresh-btn:hover {
    background: #2563eb;
}

.qrcode-loading {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 220px;
    height: 220px;
    border: 2px dashed #e5e7eb;
    border-radius: 12px;
    margin: 0 auto;
}

.qrcode-tips {
    display: flex;
    justify-content: space-around;
    margin-top: 1rem;
}

.tip-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 0.875rem;
    color: #6b7280;
    gap: 0.5rem;
}

.tip-item i {
    font-size: 1.5rem;
}

/* 微信授权样式 */
.wechat-auth {
    padding: 1rem 2rem 2rem;
}

.auth-info {
    margin-bottom: 2rem;
}

.info-item {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 1rem;
    padding: 0.75rem;
    background: #f9fafb;
    border-radius: 8px;
    font-size: 0.875rem;
    color: #374151;
    gap: 0.5rem;
}

.info-item i {
    font-size: 1.25rem;
}

.auth-actions {
    text-align: center;
}

.auth-btn {
    background: #07c160;
    color: white;
    border: none;
    padding: 1rem 2rem;
    border-radius: 8px;
    font-size: 1rem;
    font-weight: 500;
    cursor: pointer;
    transition: background-color 0.2s;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    gap: 0.5rem;
    min-width: 200px;
}

.auth-btn:hover {
    background: #06ad56;
}

/* 登录结果样式 */
.login-result {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.95);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1002;
    backdrop-filter: blur(2px);
}

.result-content {
    text-align: center;
    padding: 2rem;
}

.result-icon {
    font-size: 3rem;
    margin-bottom: 1rem;
}

.result-title {
    font-size: 1.5rem;
    font-weight: 600;
    margin-bottom: 0.5rem;
    color: #111827;
}

.result-message {
    color: #6b7280;
    font-size: 0.875rem;
}

/* 响应式设计 */
@media (max-width: 640px) {
    .social-login-container {
        margin: 1rem;
        max-width: calc(100vw - 2rem);
    }

    .login-header {
        padding: 1.5rem 1.5rem 1rem;
    }

    .pc-login,
    .wechat-auth {
        padding: 1rem 1.5rem 1.5rem;
    }

    .qrcode-image {
        width: 180px;
        height: 180px;
    }

    .qrcode-loading {
        width: 200px;
        height: 200px;
    }

    .qrcode-tips {
        flex-direction: column;
        gap: 1rem;
    }

    .auth-btn {
        min-width: 100%;
    }
}
</style>
